﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using MathematicallySafe.HeadCounter.Commands;
using MathematicallySafe.HeadCounter.Data.Common;
using MathematicallySafe.HeadCounter.Data.Models;
using MathematicallySafe.Armourer;
using MathematicallySafe.Armourer.Base;
using MathematicallySafe.HeadCounter.Data;
using MathematicallySafe.HeadCounter.Services;
using StructureMap;

namespace MathematicallySafe.HeadCounter.ViewModels
{
    public class LootViewModel: ViewModelBase
    {
        private static readonly IArmouryService ArmouryService = ArmouryServiceFactory.Instance.GetArmouryService();
        private static readonly IHeadCounterService HeadCounterService = ObjectFactory.GetInstance<IHeadCounterService>();

        private Dispatcher _dispatcher;
        private ObservableCollection<LootItemViewModel> _lootTable;

        public LootViewModel()
        {
            _dispatcher = Dispatcher.CurrentDispatcher;
            LoadLootTable();
            Initialise();
        }

        private void LoadLootTable()
        {
            LootTable = new ObservableCollection<LootItemViewModel>();
            HeadCounterService.LootTable.Items.ForEach(i => LootTable.Add(new LootItemViewModel(i)));
        }

        protected override void SubscribeEvents()
        {
            HeadCounterService.LootTable.ItemDownloaded += LootTableItemDownloaded;
        }

        protected override void UnsubscribeEvents()
        {
            HeadCounterService.LootTable.ItemDownloaded -= LootTableItemDownloaded;
        }

        public ObservableCollection<LootItemViewModel> LootTable
        {
            get { return _lootTable; }
            private set
            {
                _lootTable = value;
                OnPropertyChanged("LootTable");
            }
        }

        public event Action LootTableUpdated;

        void LootTableItemDownloaded(object sender, ItemDownloadedEventArgs e)
        {
            if (!ArmouryService.IsWorking())
            {
                Action loader = LoadLootTable;

                // todo work out why the notication isn't working and remove this hack.
                if (LootTableUpdated != null)
                {
                    _dispatcher.BeginInvoke(DispatcherPriority.Normal, loader);
                }
            }
        }
    }
}
